#include "packetcap.h"
#include <QDebug>
#include "packetcapapi.h"

#define emit_error(errbuf)  qCritical() << errbuf; emit errorString(errbuf)

CPacketCap::CPacketCap(QObject *parent) : QObject(parent)
{

}

CPacketCap::~CPacketCap()
{
    clear_host();
    clear_handles();
    clear_packets();
    clear_send_queues();
}

bool CPacketCap::init()
{
    if (!g_packetDll.isLoaded()) {
        if (!g_packetDll.load()) {
            emit_error(g_packetDll.errorString());
            return false;
        }
    }
    if (!g_wpcapDll.isLoaded()) {
        if (!g_wpcapDll.load()) {
            emit_error(g_wpcapDll.errorString());
            return false;
        }
    }
    m_version = wpcap_api(pcap_lib_version);
    return true;
}

QString CPacketCap::version() const
{
    return m_version;
}

CPCapHost *CPacketCap::newHost()
{
    CPCapHost *host = new CPCapHost();
    m_hosts.append(host);
    return host;
}

void CPacketCap::delHost(CPCapHost *host)
{
    m_hosts.removeAll(host);
    delete host;
}

CPCapHandle* CPacketCap::newHandle()
{
    CPCapHandle *handle = new CPCapHandle();
    m_handles.append(handle);
    return handle;
}

void CPacketCap::delHandle(CPCapHandle *handle)
{
    m_handles.removeAll(handle);
    delete handle;
}

CPCapPacket *CPacketCap::newPacket()
{
    CPCapPacket *packet = new CPCapPacket();
    m_packets.append(packet);
    return packet;
}

void CPacketCap::delPacket(CPCapPacket *handle)
{
    m_packets.removeAll(handle);
    delete handle;
}

CPCapSendQueue *CPacketCap::newSendQueue()
{
    CPCapSendQueue *queue = new CPCapSendQueue();
    m_sendQueues.append(queue);
    return queue;
}

void CPacketCap::delSendQueue(CPCapSendQueue *sendQueue)
{
    m_sendQueues.removeAll(sendQueue);
    delete sendQueue;
}

void CPacketCap::clear_host()
{
    foreach (CPCapHost *host, m_hosts) {
        delete host;
    }
    m_hosts.clear();
}

void CPacketCap::clear_handles()
{
    foreach (CPCapHandle *handle, m_handles) {
        delete handle;
    }
    m_handles.clear();
}

void CPacketCap::clear_packets()
{
    foreach (CPCapPacket *packet, m_packets) {
        delete packet;
    }
    m_packets.clear();
}

void CPacketCap::clear_send_queues()
{
    foreach (CPCapSendQueue *queue, m_sendQueues) {
        delete queue;
    }
    m_sendQueues.clear();
}
